<script setup lang="ts">
import {
  userData,
  genData,
  tqType
} from "@/views/marketForecast/loadForecasting/testData";
import VChart from "@/views/monitor/server/components/VChart.vue";
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import { Grid, Plus, RefreshLeft, Search } from "@element-plus/icons-vue";
import { ElForm, ElMessage, ElNotification } from "element-plus";
import moment from "moment";
import { dayRangeArray, timeSlot } from "@/utils";
import { jiejiaList } from "@/views/systemLoadForecasting/systemLoadForecastingBaseMessage/holidays/testData";
const route = useRoute();
const activeName = ref("first");
const allUser = reactive({
  data: userData
});
const users = computed(() => {
  if (queryForm.data.activeVppId) {
    let parent = userData.find(item => item.id === queryForm.data.activeVppId);
    if (parent.children) {
      return parent.children;
    } else {
      return [];
    }
  } else {
    return [];
  }
});
const terms = computed(() => {
  if (queryForm.data.activeUserId) {
    let parent = users.value.find(
      item => item.id === queryForm.data.activeUserId
    );
    if (parent.children) {
      return parent.children;
    } else {
      return [];
    }
  } else {
    return [];
  }
});
const shebeis = computed(() => {
  if (queryForm.data.activeTermId) {
    let parent = terms.value.find(
      item => item.id === queryForm.data.activeTermId
    );
    if (parent.children) {
      return parent.children;
    } else {
      return [];
    }
  } else {
    return [];
  }
});
const vppChange = () => {
  queryForm.data.activeUserId = undefined;
  queryForm.data.activeTermId = undefined;
};
const userChange = () => {
  queryForm.data.activeTermId = undefined;
  queryForm.data.activeSbId = undefined;
};
const termChange = () => {
  queryForm.data.activeSbId = undefined;
};
const queryForm = reactive({
  data: {
    activeVppId: undefined,
    activeUserId: undefined,
    activeTermId: undefined,
    activeSbId: undefined,
    activeTime: []
  }
});
const options = ref({
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    splitLine: {
      show: true,
      interval: (index, value) => {
        if (value.indexOf("00:00:00") > -1) {
          return true;
        } else {
          return false;
        }
      },
      lineStyle: {
        type: "solid",
        width: 1.3
      }
    },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: "value",
    min: 1000
  },
  series: [
    {
      name: "负荷数据",
      type: "line",
      symbol: "circle",
      showSymbol: true,
      symbolSize: 6,
      smooth: true,
      markPoint: {
        //给第一条y轴添加标记点
        data: []
      },
      data: []
    }
  ]
});
const loading = ref(false);
const init = async () => {
  queryForm.data.activeTime = moment().subtract("day", -1).format("YYYY-MM-DD");
  dataFormat([]);
};

const search = async () => {
  if (
    queryForm.data.activeTime &&
    (queryForm.data.activeVppId || queryForm.data.activeUserId)
  ) {
    dataFormat(genData(queryForm.data.activeTime, queryForm.data.activeTime));
  } else {
    dataFormat([]);
  }
};
const resetQuery = () => {
  queryForm.data = {
    activeVppId: undefined,
    activeUserId: undefined,
    activeTermId: undefined,
    activeSbId: undefined,
    activeTime: moment().subtract("day", -1).format("YYYY-MM-DD")
  };
};
const keys = ref(
  Array(96)
    .fill(1)
    .map((_, index) => index + 1)
    .map(i => `p${i > 9 ? i : "0" + i}`)
);
const showData = reactive({
  data: []
});
const times = ref(timeSlot(15));
const dataFormat = data => {
  let days = [];
  if (queryForm.data.activeTime) {
    days = [queryForm.data.activeTime];
  } else {
    days = [];
  }
  let allData = [];
  let xData = [];
  days.forEach(i => {
    new Array(2).fill(1).forEach((z, zindex) => {
      let item = {};
      item.dataDate = i + " 00:00:00";
      keys.value.forEach(key => {
        item[key] = null;
      });
      item.dataType = zindex + 1;
      allData.push(item);
    });
  });
  for (let i = 0; i < allData.length; i++) {
    for (let j = 0; j < data.length; j++) {
      if (
        allData[i].dataDate === data[j].dataDate &&
        allData[i].dataType === data[j].dataType
      ) {
        allData[i] = Object.assign({}, allData[i], data[j]);
      }
    }
  }
  const ret = {};
  allData.forEach(i => {
    ret[i.dataDate] = {
      "1": {},
      "2": {}
    };
  });
  allData.forEach(i => {
    ret[i.dataDate][i.dataType + ""] = i;
  });

  let oneData = allData.filter(i => i.dataType === 1);
  let isd = [];
  oneData.forEach(i => {
    times.value.forEach((z, index) => {
      xData.push(i.dataDate.split(" ")[0] + " " + z + ":00");
      isd.push({
        value: i[keys.value[index]]
      });
    });
  });
  start.value = (1 - 96 / xData.length) * 100;
  options.value.xAxis.data = xData;
  options.value.dataZoom[0].start = start.value;
  options.value.dataZoom[1].start = start.value;

  options.value.series[0].data = isd;
  showData.data = [];
  xData.forEach((item, index) => {
    let v = {
      label: item,
      value: isd[index].value
    };
    showData.data.push(v);
  });
  showData.data.sort((a, b) => {
    return Date.parse(a.label) - Date.parse(b.label);
  });
};
const columns = [
  {
    key: "label",
    dataKey: "label",
    title: "时间",
    width: "50%"
  },
  {
    key: "value",
    dataKey: "value",
    title: "负荷数据",
    width: "50%"
  }
];
onMounted(() => {
  init();
});
const start = ref(0);
const end = ref(100);
const dataZoomEvent = e => {
  if (e.batch && e.batch.length) {
    start.value = e.batch[0].start;
    end.value = e.batch[0].end;
  } else {
    start.value = e.start;
    end.value = e.end;
  }
};
const zdxz = () => {
  if (
    queryForm.data.activeTime &&
    (queryForm.data.activeVppId || queryForm.data.activeUserId)
  ) {
    let bool = showData.data.every(i => i.value);
    if (bool) {
      let newData = showData.data.map(item => {
        if (parseFloat(item.value) <= 1100) {
          item.value = 1100;
        }
        return item;
      });
      showData.data = newData;
      options.value.series[0].data = newData.map(item => {
        return {
          value: item.value
        };
      });
      options.value.dataZoom[0].start = start.value;
      options.value.dataZoom[0].end = end.value;
      options.value.dataZoom[1].start = start.value;
      options.value.dataZoom[1].end = end.value;
    }
  }
};
const ycfx = () => {
  if (
    queryForm.data.activeTime &&
    (queryForm.data.activeVppId || queryForm.data.activeUserId)
  ) {
    showData.data.forEach(item => {
      // 突变、连续恒定、空值、0值
      if (parseFloat(item.value) <= 1200 && parseFloat(item.value) > 1150) {
        options.value.series[0].markPoint.data.push({
          value: "突变",
          xAxis: item.label,
          yAxis: item.value,
          itemStyle: {
            color: "red" //颜色设置为红色
          }
        });
      }
      if (parseFloat(item.value) <= 1150 && parseFloat(item.value) > 1100) {
        options.value.series[0].markPoint.data.push({
          value: "连续恒定",
          xAxis: item.label,
          yAxis: item.value,
          itemStyle: {
            color: "red" //颜色设置为红色
          }
        });
      }
      if (parseFloat(item.value) <= 1100 && parseFloat(item.value) > 1050) {
        options.value.series[0].markPoint.data.push({
          value: "空值",
          xAxis: item.label,
          yAxis: item.value,
          itemStyle: {
            color: "red" //颜色设置为红色
          }
        });
      }
      if (parseFloat(item.value) <= 1050 && parseFloat(item.value) > 1000) {
        options.value.series[0].markPoint.data.push({
          value: "0值",
          xAxis: item.label,
          yAxis: item.value,
          itemStyle: {
            color: "red" //颜色设置为红色
          }
        });
      }
    });
  }
};
const addDialog = ref(false);
const editDialog = ref(false);
const form = reactive({
  data: {
    oritime: undefined,
    sd: undefined,
    begin: undefined,
    end: undefined
  },
  rules: {
    oritime: [{ required: true, message: "请选择源日期", trigger: "change" }],
    sd: [{ required: true, message: "请选择时段", trigger: "change" }]
  }
});
const tform = reactive({
  data: {
    time: undefined,
    beforeData: undefined,
    value: undefined
  },
  rules: {
    time: [{ required: true, message: "请选择时刻", trigger: "change" }],
    value: [{ required: true, message: "请输入修正数据", trigger: "change" }]
  }
});
const tchange = e => {
  let item = showData.data.find(i => i.label.indexOf(e) > -1);
  if (item) {
    tform.data.beforeData = item.value;
  } else {
    tform.data.beforeData = "";
  }
};
const bchange = e => {
  if (e && form.data.end) {
    form.data.sd = e + "-" + form.data.end;
  } else {
    form.data.sd = undefined;
  }
};
const echange = e => {
  if (e && form.data.begin) {
    form.data.sd = form.data.begin + "-" + e;
  } else {
    form.data.sd = undefined;
  }
};
const formRules = ref(null);
const tformRules = ref(null);
const cancel = () => {
  form.data = {
    oritime: undefined,
    sd: undefined,
    begin: undefined,
    end: undefined
  };
  setTimeout(() => {
    formRules.value.clearValidate();
    addDialog.value = false;
  }, 0);
};
const beforeClose = async d => {
  await cancel();
  d();
};
const submit = () => {
  formRules.value.validate(valid => {
    if (valid) {
      ElNotification({
        title: "系统提示",
        message: "复制成功",
        type: "success"
      });
      cancel();
    }
  });
};
const tcancel = () => {
  tform.data = {
    time: undefined,
    beforeData: undefined,
    value: undefined
  };
  setTimeout(() => {
    tformRules.value.clearValidate();
    editDialog.value = false;
  }, 0);
};
const tbeforeClose = async d => {
  await tcancel();
  d();
};
const tsubmit = () => {
  tformRules.value.validate(valid => {
    if (valid) {
      showData.data.forEach(item => {
        if (item.label.indexOf(tform.data.time) > -1) {
          item.value = tform.data.value;
        }
      });
      let copyData = JSON.parse(JSON.stringify(showData.data));
      copyData.reverse();
      options.value.series[0].data = copyData.map(item => {
        return {
          value: item.value
        };
      });
      ElNotification({
        title: "系统提示",
        message: "修改成功",
        type: "success"
      });
      tcancel();
    }
  });
};
const dataCopy = () => {
  addDialog.value = true;
};
const sdxz = () => {
  editDialog.value = true;
};
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-dialog
      v-model="editDialog"
      :before-close="tbeforeClose"
      title="手动修正"
      width="40%"
    >
      <div class="w-full">
        <el-form
          ref="tformRules"
          class="display-block"
          :model="tform.data"
          label-width="120px"
          :rules="tform.rules"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="时刻" prop="time">
                <el-select v-model="tform.data.time" @change="tchange">
                  <el-option
                    v-for="item in times"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="修正前数据" prop="beforeData">
                <span>{{ tform.data.beforeData }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="修正数据" prop="value">
                <el-input v-model="tform.data.value" placeholder="修正数据" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tcancel">取消</el-button>
          <el-button type="primary" @click="tsubmit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="addDialog"
      :before-close="beforeClose"
      title="选择复制日期"
      width="40%"
    >
      <div class="w-full">
        <el-form
          ref="formRules"
          class="display-block"
          :model="form.data"
          label-width="120px"
          :rules="form.rules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="源日期" prop="oritime">
                <el-date-picker
                  v-model="form.data.oritime"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                  date-format="YYYY-MM-DD"
                  :size="'default'"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择时段" prop="sd">
                <div class="flex align-center">
                  <el-select
                    v-model="form.data.begin"
                    style="width: 90px"
                    @change="bchange"
                  >
                    <el-option
                      v-for="item in times"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                  <span class="px-[10px]">-</span>
                  <el-select
                    v-model="form.data.end"
                    style="width: 90px"
                    @change="echange"
                  >
                    <el-option
                      v-for="item in times"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-form :inline="true" :model="queryForm.data" label-width="0px">
        <el-form-item>
          <el-select
            v-model="queryForm.data.activeVppId"
            placeholder="选择场站"
            style="width: 240px"
            @change="vppChange"
          >
            <el-option
              v-for="item in allUser.data"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryForm.data.activeUserId"
            placeholder="选择用户"
            style="width: 240px"
            @change="userChange"
          >
            <el-option
              v-for="item in users"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-select-->
        <!--            v-model="queryForm.data.activeTermId"-->
        <!--            placeholder="选择终端"-->
        <!--            style="width: 240px"-->
        <!--            @change="termChange"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in terms"-->
        <!--              :key="item.id"-->
        <!--              :value="item.id"-->
        <!--              :label="item.name"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item>-->
        <!--          <el-select-->
        <!--            v-model="queryForm.data.activeSbId"-->
        <!--            placeholder="选择设备"-->
        <!--            style="width: 240px"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in shebeis"-->
        <!--              :key="item.id"-->
        <!--              :value="item.id"-->
        <!--              :label="item.name"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-date-picker
            v-model="queryForm.data.activeTime"
            type="date"
            value-format="YYYY-MM-DD"
            date-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item class="ml-[10px]">
          <el-button type="primary" :icon="Search" @click="search"
            >查询</el-button
          >
          <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="ycfx">异常分析</el-button>
          <el-button type="primary" @click="zdxz">自动修正</el-button>
          <el-button type="primary" @click="dataCopy">数据复制</el-button>
          <el-button type="primary" @click="sdxz">手动修正</el-button>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="图表" name="first">
          <div class="w-full h-full">
            <v-chart :options="options" @dataZoom="dataZoomEvent" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="列表" name="second">
          <div>
            <!--            <el-table :data="showData.data" height="600px" border>-->
            <!--              <el-table-column prop="time" label="时间" />-->
            <!--              <el-table-column prop="value" label="实时数据" />-->
            <!--            </el-table>-->
            <el-table-v2
              :columns="columns"
              :data="showData.data"
              :width="1614"
              :height="600"
              :scrollbar-always-on="false"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .demo-tabs {
      display: flex;
      flex: 1;
      flex-direction: column;
      overflow: hidden;

      .el-tabs__content {
        flex: 1;

        .el-tab-pane {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
